<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>Bun Learning</h1>
        <p>欢迎登录学习系统</p>
      </div>
      
      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 传统登录 -->
        <el-tab-pane label="账号登录" name="account">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @submit.prevent="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="authStore.loading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 微信扫码登录 -->
        <el-tab-pane label="微信登录" name="wechat">
          <div class="wechat-login">
            <div v-if="!qrCode" class="wechat-placeholder">
              <el-button
                type="primary"
                size="large"
                :loading="authStore.loading"
                @click="handleWeChatLogin"
              >
                获取微信登录二维码
              </el-button>
            </div>
            
            <div v-else class="qr-code-container">
              <div class="qr-code">
                <img :src="qrCode" alt="微信登录二维码" />
                <p>请使用微信扫描二维码登录</p>
              </div>
              
              <div class="qr-status">
                <el-tag :type="statusType">{{ statusText }}</el-tag>
              </div>
              
              <el-button
                type="text"
                @click="refreshQRCode"
                :loading="authStore.loading"
              >
                刷新二维码
              </el-button>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 用户注册 -->
        <el-tab-pane label="注册账号" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="login-form"
            @submit.prevent="handleRegister"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                size="large"
                prefix-icon="Message"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                size="large"
                prefix-icon="Lock"
                show-password
                @keyup.enter="handleRegister"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="authStore.loading"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import type { LoginForm, RegisterForm } from '@/types/auth'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// 当前激活的标签页
const activeTab = ref('account')

// 登录表单
const loginForm = reactive<LoginForm>({
  username: '',
  password: ''
})

// 注册表单
const registerForm = reactive<RegisterForm>({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 微信登录相关
const qrCode = ref('')
const wechatState = ref('')
const wechatStatus = ref<'pending' | 'scanned' | 'confirmed' | 'expired'>('pending')
const statusTimer = ref<NodeJS.Timeout | null>(null)

// 登录表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 微信登录状态文本
const statusText = computed(() => {
  switch (wechatStatus.value) {
    case 'pending':
      return '等待扫码'
    case 'scanned':
      return '已扫码，等待确认'
    case 'confirmed':
      return '登录成功'
    case 'expired':
      return '二维码已过期'
    default:
      return '未知状态'
  }
})

// 微信登录状态类型
const statusType = computed(() => {
  switch (wechatStatus.value) {
    case 'pending':
      return 'info'
    case 'scanned':
      return 'warning'
    case 'confirmed':
      return 'success'
    case 'expired':
      return 'danger'
    default:
      return 'info'
  }
})

// 传统登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    const result = await authStore.loginUser(loginForm)
    
    if (result.success) {
      router.push('/dashboard')
    }
  } catch (error) {
    console.error('登录失败:', error)
  }
}

// 用户注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    const result = await authStore.registerUser(registerForm)
    
    if (result.success) {
      // 注册成功后切换到登录标签页
      activeTab.value = 'account'
      // 清空注册表单
      Object.assign(registerForm, {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      })
    }
  } catch (error) {
    console.error('注册失败:', error)
  }
}

// 微信登录
const handleWeChatLogin = async () => {
  const result = await authStore.loginWithWeChat()
  
  if (result.success) {
    qrCode.value = result.qrCode
    wechatState.value = result.state
    wechatStatus.value = 'pending'
    
    // 开始轮询状态
    startStatusPolling()
  }
}

// 刷新二维码
const refreshQRCode = () => {
  stopStatusPolling()
  qrCode.value = ''
  wechatState.value = ''
  wechatStatus.value = 'pending'
  handleWeChatLogin()
}

// 开始轮询微信登录状态
const startStatusPolling = () => {
  if (statusTimer.value) {
    clearInterval(statusTimer.value)
  }
  
  statusTimer.value = setInterval(async () => {
    if (!wechatState.value) return
    
    const result = await authStore.checkWeChatLoginStatus(wechatState.value)
    
    if (result.success) {
      wechatStatus.value = result.data.status
      
      if (result.data.status === 'confirmed') {
        // 登录成功
        stopStatusPolling()
        ElMessage.success('微信登录成功')
        router.push('/dashboard')
      } else if (result.data.status === 'expired') {
        // 二维码过期
        stopStatusPolling()
        ElMessage.warning('二维码已过期，请刷新')
      }
    }
  }, 2000) // 每2秒检查一次
}

// 停止轮询
const stopStatusPolling = () => {
  if (statusTimer.value) {
    clearInterval(statusTimer.value)
    statusTimer.value = null
  }
}

// 组件挂载时检查是否已登录
onMounted(() => {
  if (authStore.isAuthenticated) {
    router.push('/dashboard')
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopStatusPolling()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px;
  position: relative;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
}

.login-box {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  padding: 40px 20px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.login-header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.login-tabs {
  padding: 20px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
}

.wechat-login {
  text-align: center;
  padding: 20px 0;
}

.wechat-placeholder {
  padding: 40px 0;
}

.qr-code-container {
  padding: 20px 0;
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 15px;
}

.qr-code p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.qr-status {
  margin: 15px 0;
}

:deep(.el-tabs__item) {
  font-weight: 500;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}
</style>
